package com.ruoyi.system.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Api(tags = "文件相关（后续改为OSS）")
@RequestMapping("/system/file")
@RestController
public class FileUploadController {

    @Value("${file.upload-dir}")
    private String uploadDir;

    @PostConstruct
    public void init() {
        try {
            Path path = Paths.get(uploadDir);
            if (!Files.exists(path)) {
                Files.createDirectories(path);
            }
        } catch (IOException e) {
            throw new RuntimeException("Could not initialize folder for upload!");
        }
    }

    @PostMapping("/upload")
    @ApiOperation("文件上传，返回路径URL")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("文件不能为空");
        }

        try {
            String originalFileName = file.getOriginalFilename();
            String fileName = System.currentTimeMillis() + "_" + originalFileName;

            // 将文件名进行URL编码
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()).replace("+", "%20");

            Path path = Paths.get(uploadDir + File.separator + fileName);
            Files.write(path, file.getBytes());

            // 使用已编码的文件名构建文件访问URL
            String fileAccessUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/system/file/download/" + encodedFileName;
            return ResponseEntity.ok(fileAccessUrl); // 返回文件访问URL

        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败");
        }
    }

    @GetMapping("/download/{fileName}")
    @ApiOperation("文件下载或预览")
    public ResponseEntity<Resource> getFile(@PathVariable String fileName, @RequestParam(defaultValue = "download") String action) {
        try {
            // 对文件名进行URL解码，防止中文乱码或特殊字符问题
            String decodedFileName = URLDecoder.decode(fileName, StandardCharsets.UTF_8.name());

            // 构建文件的完整路径
            Path filePath = Paths.get(uploadDir, decodedFileName);

            // 检查文件是否存在
            if (!Files.exists(filePath)) {
                return ResponseEntity.notFound().build();
            }

            // 创建资源对象，用于封装文件资源
            Resource file = new UrlResource(filePath.toUri());

            // 对文件名进行URL编码，防止中文乱码或特殊字符问题
            String encodedFileName = URLEncoder.encode(decodedFileName, StandardCharsets.UTF_8.name()).replace("+", "%20");

            // 根据action参数确定Content-Disposition头：inline为预览，attachment为下载
            String disposition = action.equals("view") ? "inline" : "attachment";  // 默认为下载模式

            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, disposition + "; filename=\"" + encodedFileName + "\"");

            // 尝试确定文件的MIME类型
            String contentType = Files.probeContentType(filePath);
            if (contentType == null) {
                contentType = "application/octet-stream";  // 无法确定MIME类型时使用二进制流，促使浏览器下载
            }
            headers.add(HttpHeaders.CONTENT_TYPE, contentType);

            // 返回响应实体，包含文件内容、头信息和HTTP状态码
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(file);
        } catch (Exception e) {
            e.printStackTrace();  // 打印异常信息至标准错误流
            return ResponseEntity.internalServerError().build();  // 发生异常时返回500内部服务器错误
        }
    }




}
